<?php
/**
 * 测试命令
 * @author yupoxiong<i@yupoxiong.com>
 */

declare (strict_types=1);


namespace app\command;

use app\common\service\DateService;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use think\facade\Cache;
use Webman\RedisQueue\Redis;

class Test extends Command
{
    protected static $defaultName = 'test';
    protected static $defaultDescription = '测试命令';

    protected function execute(InputInterface $input, OutputInterface $output): int
    {

        $this->testSetLock($output);

        return self::SUCCESS;
    }

    /**
     * @param OutputInterface $output
     */
    public function testSetLock($output)
    {
        $msg = [];
        for($i=1;$i<=500;$i++){
            $msg[]=  $this->setLock();
        }
        foreach ($msg as $item){
            $output->writeln($item);
        }
    }

    public function testSetNxLock($output)
    {
        $msg = [];
        for($i=1;$i<=500;$i++){
           $msg[]= $this->setNxLock();
        }

        foreach ($msg as $item){
            $output->writeln($item);
        }
    }


    public function setLock()
    {
        /** @var \Redis $redis */
        $redis = Cache::handler();

        $lock_key = 'test_lock_key_set_20140110001';

        $lock = $redis->get($lock_key);
        if ($lock) {
            return '<error>SET已锁住</error>';
        }

        // 锁10秒
        $redis->set($lock_key, 1, 10);

        return'<info>SET未锁</info>';

    }

    public function setNxLock()
    {
        /** @var \Redis $redis */
        $redis = Cache::handler();

        $lock_key = 'test_lock_key_set_nx_20140110001';


        $lock = $redis->setnx($lock_key, 1);
        if ($lock) {
            $redis->expire($lock_key, 10);
            return'<info>SET_NX未锁</info>';
        }

        return '<error>SET_NX已锁住</error>';
    }

    public function getAllWords($content)
    {
        preg_match_all("/([a-zA-Z]+)/", $content, $result);
        return $result;
    }


    // 测试队列
    protected function testQueue()
    {
        // 队列名
        $queue = 'test_queue';
        // 数据，可以直接传数组，无需序列化
        $data = ['number' => DateService::microTimestamp()];
        // 投递消息
        Redis::send($queue, $data);
    }
}